import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入Login的路由
import Login from '../views/Login.vue'
// 导入Home的路由
import Home from '../views/Home.vue'
// 导入欢迎界面的路由
import Welcome from '../views/Welcome.vue'
// 导入用户列表
import Users from '../views/Users/Users.vue'

// 导入权限的路由
import Rights from '../views/Power/Rights.vue'

// 导入角色管理路由
import Roles from '../views/Power/Roles.vue'

// 导入商品分类
import Category from '../views/Goods/Category.vue'

// 导入分类参数
import Params from '../views/Goods/Params.vue'

// 导入商品列表
import GoodList from '../views/Goods/GoodList.vue'

// 导入添加商品
import Add from '../views/Goods/Add.vue'

// 导入订单商品
import Orders from '../views/Order/Orders.vue'

// 导入数据商品
import Report from '@/views/Report/Reports.vue'
Vue.use(VueRouter)

const routes = [
  // 定义Login的路由规则
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodList },
      { path: '/goods/addgood', component: Add },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Report }
    ]
  }]

const router = new VueRouter({
  routes
})

// 使用路由导航守卫来界定,如果没有token时候就跳回到登录界面 全局配置守卫
router.beforeEach((to, from, next) => {
  // to -- 表示将要进入的路由目标
  // from -- 表示导航要离开的界面
  // next -- 放行的界面
  // 如果用户访问了登陆页面直接放行
  if (to.path === '/login') return next()
  // 先获取token的值，如果token的值为空 就强制跳转到登录界面 不是空就可以随意跳转
  const myToken = window.sessionStorage.getItem('token')
  // 如果值是空的 强制跳转
  if (!myToken) return next('/login')
  // 不是空值随意跳转
  next()
})
// 修改多次点击登录按钮产生bug的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
